package com.zhichat.web.socket.netty;

import com.zhichat.infrastructure.config.ZhiChatConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

/**
 * @ClassName: NettyWsInit
 * @Description: netty框架初始化
 * @Author: 团长九哥 https://space.bilibili.com/602197686
 * @CreateDate: 2024/11/29 16:31
 */
@Slf4j
@Component
@AllArgsConstructor
public class NettyWsInit implements DisposableBean {

    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(1); // boss线程组
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(); // worker线程组
    private final ZhiChatConfig zhiChatConfig;
    private final WsInitHandler wsInitHandler;

    public void start() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(wsInitHandler);
        try {
            Channel channel = serverBootstrap.bind(zhiChatConfig.getWsPort()).sync().channel();
            log.info("netty服务启动成功，监听端口：{}", zhiChatConfig.getWsPort());
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
